/**
 * jQuery JSON plugin 2.4.0
 *
 * @author Brantley Harris, 2009-2011
 * @author Timo Tijhof, 2011-2012
 * @source This plugin is heavily influenced by MochiKit's serializeJSON, which is
 *         copyrighted 2005 by Bob Ippolito.
 * @source Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
 *         website's http://www.json.org/json2.js, which proclaims:
 *         "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 *         I uphold.
 * @license MIT License <http://www.opensource.org/licenses/mit-license.php>
 */
 
(function ($) {
	'use strict';

	var escape = /["\\\x00-\x1f\x7f-\x9f]/g,
		meta = {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"' : '\'',
			'\\': '\\\\'
		},
		hasOwn = Object.prototype.hasOwnProperty;

	/**
	 * jQuery.toJSON
	 * Converts the given argument into a JSON representation.
	 *
	 * @param o {Mixed} The json-serializable *thing* to be converted
	 *
	 * If an object has a toJSON prototype, that will be used to get the representation.
	 * Non-integer/string keys are skipped in the object, as are keys that point to a
	 * function.
	 *
	 */
	$.toJSON = typeof JSON === 'object' && JSON.stringify ? JSON.stringify : function (o) {
		if (o === null) {
			return 'null';
		}

		var pairs, k, name, val,
			type = $.type(o);

		if (type === 'undefined') {
			return undefined;
		}

		// Also covers instantiated Number and Boolean objects,
		// which are typeof 'object' but thanks to $.type, we
		// catch them here. I don't know whether it is right
		// or wrong that instantiated primitives are not
		// exported to JSON as an {"object":..}.
		// We choose this path because that's what the browsers did.
		if (type === 'number' || type === 'boolean') {
			return String(o);
		}
		if (type === 'string') {
			return $.quoteString(o);
		}
		if (typeof o.toJSON === 'function') {
			return $.toJSON(o.toJSON());
		}
		if (type === 'date') {
			var month = o.getUTCMonth() + 1,
				day = o.getUTCDate(),
				year = o.getUTCFullYear(),
				hours = o.getUTCHours(),
				minutes = o.getUTCMinutes(),
				seconds = o.getUTCSeconds(),
				milli = o.getUTCMilliseconds();

			if (month < 10) {
				month = '0' + month;
			}
			if (day < 10) {
				day = '0' + day;
			}
			if (hours < 10) {
				hours = '0' + hours;
			}
			if (minutes < 10) {
				minutes = '0' + minutes;
			}
			if (seconds < 10) {
				seconds = '0' + seconds;
			}
			if (milli < 100) {
				milli = '0' + milli;
			}
			if (milli < 10) {
				milli = '0' + milli;
			}
			return '"' + year + '-' + month + '-' + day + 'T' +
				hours + ':' + minutes + ':' + seconds +
				'.' + milli + 'Z"';
		}

		pairs = [];

		if ($.isArray(o)) {
			for (k = 0; k < o.length; k++) {
				pairs.push($.toJSON(o[k]) || 'null');
			}
			return '[' + pairs.join(',') + ']';
		}

		// Any other object (plain object, RegExp, ..)
		// Need to do typeof instead of $.type, because we also
		// want to catch non-plain objects.
		if (typeof o === 'object') {
			for (k in o) {
				// Only include own properties,
				// Filter out inherited prototypes
				if (hasOwn.call(o, k)) {
					// Keys must be numerical or string. Skip others
					type = typeof k;
					if (type === 'number') {
						name = '"' + k + '"';
					} else if (type === 'string') {
						name = $.quoteString(k);
					} else {
						continue;
					}
					type = typeof o[k];

					// Invalid values like these return undefined
					// from toJSON, however those object members
					// shouldn't be included in the JSON string at all.
					if (type !== 'function' && type !== 'undefined') {
						val = $.toJSON(o[k]);
						pairs.push(name + ':' + val);
					}
				}
			}
			return '{' + pairs.join(',') + '}';
		}
	};

	/**
	 * jQuery.evalJSON
	 * Evaluates a given json string.
	 * 格式化json
	 * @param str {String}
	 */
	$.evalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function (str) {
		/*jshint evil: true */
		return eval('(' + str + ')');
	};

	/**
	 * jQuery.secureEvalJSON
	 * Evals JSON in a way that is *more* secure.
	 * 安全环境下格式化json
	 * @param str {String}
	 */
	$.secureEvalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function (str) {
		var filtered =
			str
			.replace(/\\["\\\/bfnrtu]/g, '@')
			.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
			.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

		if (/^[\],:{}\s]*$/.test(filtered)) {
			/*jshint evil: true */
			return eval('(' + str + ')');
		}
		throw new SyntaxError('Error parsing JSON, source is not valid.');
	};

	/**
	 * jQuery.quoteString
	 * Returns a string-repr of a string, escaping quotes intelligently.
	 * Mostly a support function for toJSON.
	 * Examples:
	 * >>> jQuery.quoteString('apple')
	 * "apple"
	 * 
	 * >>> jQuery.quoteString('"Where are we going?", she asked.')
	 * "'Where are we going?', she asked."
	 */
	$.quoteString = function (str) {
		if (str.match(escape)) {
			return '"' + str.replace(escape, function (a) {
				var c = meta[a];
				if (typeof c === 'string') {
					return c;
				}
				c = a.charCodeAt();
				return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
			}) + '"';
		}
		return '"' + str + '"';
	};
	/**
	 * 处理IE6下面png图片问题
	 */
	$.correctPNG = function(){
        var arVersion = navigator.appVersion.split("MSIE")
        var version = parseFloat(arVersion[1])
        if ((version >= 5.5) && (document.body.filters)) {
            for (var j = 0; j < document.images.length; j++) {
                var img = document.images[j]
                var imgName = img.src.toUpperCase()
                if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
                    var imgID = (img.id) ? "id='" + img.id + "' " : ""
                    var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                    var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                    var imgStyle = "display:inline-block;" + img.style.cssText
                    if (img.align == "left") imgStyle = "float:left;" + imgStyle
                    if (img.align == "right") imgStyle = "float:right;" + imgStyle
                    if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                    var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                    img.outerHTML = strNewHTML
                    j = j - 1
                }
            }
        }
    }
	/**********************************
	 * 自定义函数
	 *********************************/
	/**
	 * 打开easyui的load提示窗体，传入dataGrid对象或者html id
	 */
	$.showLoadMsg = function(grid) {
		var dt = (typeof grid === "string") ? $('#' + grid) : grid;
		var _593 = dt.datagrid("getPanel");
		$("<div class='datagrid-mask' style='display:block'></div>").appendTo(_593);
		var msg = $("<div class='datagrid-mask-msg' style='display:block'></div>").html($.fn.datagrid.defaults.loadMsg).appendTo(_593);
		msg.css("left", (_593.width() - msg._outerWidth()) / 2);
	};
	/**
	 * 隐藏easyui的load提示窗体，传入dataGrid对象或者html id
	 */
	$.hideLoadMsg = function(grid) {
		var dt = (typeof grid === "string") ? $('#' + grid) : grid;
		var _594 = dt.datagrid("getPanel");
		_594.children("div.datagrid-mask-msg").remove();
		_594.children("div.datagrid-mask").remove();
	};
	/**
	 * 在DataGrid中获取所选记录的id数组 
	 * 注：该方法使用的前提是：DataGrid的idField属性对应到列表Json数据中的字段名必须为id
	 * 
	 * @param dataTableId目标记录所在的DataGrid列表table的id
	 * @return 所选记录的id数组
	 */
	$.getCheckedIds = function(dataTableId, noOneSelectMessage) {
		var rows = $('#' + dataTableId).datagrid('getChecked');
		var ids = [], num = rows.length;
		if (num < 1 && null != noOneSelectMessage) {
			$.messager.confirm('提示消息', noOneSelectMessage, function(r) {
				if (!r) {
					return false;
				}
			});
		} else {
			for ( var i = 0; i < num; i++) {
				ids.push(rows[i].id);
			}
		}
		return ids;
	};
	$.checkGridRow = function(grid, id, check) {
		var dt = $('#' + grid);
		if (check) {
			dt.datagrid('checkRow', dt.datagrid('getRowIndex', id));
		} else {
			dt.datagrid('uncheckRow', dt.datagrid('getRowIndex', id));
		}
	}
	/**
	 * 在ComboTree多选树中获取所选记录的id数组
	 * 
	 * @param comboTreeId目标记录所在的ComboTree组件的id
	 * @return 所选记录的id数组
	 */
	$.getComboTreeIds = function(comboTreeId) {
		var nodes = $('#' + comboTreeId).combotree('getValues'), ids = [];
		for ( var i = 0, l = nodes.length; i < l; i++) {
			if (nodes[i] > 0) {
				ids.push(nodes[i]);
			}
		}
		return ids;
	};
	/**
	 * 监听DataGrid组件记录的选择操作，包括onCheck、onUncheck、onCheckAll、onUncheckAll四个事件
	 * 注：该方法使用的前提是：DataGrid的idField属性对应到列表Json数据中的字段名必须为id
	 * 
	 * @param dataTableId目标记录所在的DataGrid列表table的id
	 */
	$.comboTreeCheckListener = function(comboTreeId, gridId, url, iframeName, callback) {
		$('#' + comboTreeId).combotree({
			onCheck : function(node, checked) {
				var ids = $.getComboTreeIds(comboTreeId);
				$('#' + comboTreeId).combotree('hidePanel');
				if (callback) {
					callback();
				}
				var dtDevices = $('#' + gridId);
				$.showLoadMsg(dtDevices);
				dtDevices.datagrid('loadData', {
					total : 0,
					rows : []
				});
				$.post(url, {ids : ids.join(',')}, function(data) {
					$.hideLoadMsg(dtDevices);
					if (data) {
						var rows = $.parseJSON(data);
						dtDevices.datagrid('loadData', rows).datagrid('checkAll');
						dtDevices.datagrid({
							onCheck : function(rowIndex, rowData) {
								iframeMap.selectOneObject(rowData.id, 2);
							},
							onUncheck : function(rowIndex, rowData) {
								iframeMap.selectOneObject(rowData.id, 1);
							},
							onCheckAll : function(rows) {
								var dtIds = [];
								for ( var i = 0, l = rows.length; i < l; i++) {
									dtIds.push(rows[i].id);
								}
								iframeMap.selectAllObject(dtIds, 2);//地图选中
							},
							onUncheckAll : function(rows) {
								iframeMap.unSelectAllObject();//地图选中
							}
						});
					}
				});
				var iframeMap = window.frames[iframeName];
				iframeMap.selectAllObject(ids, 2);//地图选中
			}
		});
	};
	/**
	 * 监听DataGrid组件记录的选择操作，包括onCheck、onUncheck、onCheckAll、onUncheckAll四个事件
	 * 注：该方法使用的前提是：DataGrid的idField属性对应到列表Json数据中的字段名必须为id
	 * 
	 * @param dataTableId目标记录所在的DataGrid列表table的id
	 * @param url：查询服务对应的url路径
	 */
	$.paginationListener = function(dataTableId, url, sortField) {
		var dt = $("#" + dataTableId);
		var pg = dt.datagrid("getPager");
		if (pg) {
			$(pg).pagination({
				onSelectPage : function(pageNumber, pageSize) {
					$.showLoadMsg(dt);
					$.post(url, $.toJSON($.getPageParam(pageNumber, pageSize, $('#tableName').val(), sortField)), function(data) {
						$.hideLoadMsg(dt);
						var rows = $.parseJSON(data);
						$('#tableName').val(rows.tableName);
						dt.datagrid('loadData', {
							"rows" : rows.listResult
						});
					});
					return;
				}
			});
		}
	};
	/**
	 * 针对开始、结束时间进行对比判断，并检查imsi和imei
	 * 
	 * @param beginTime：开始时间
	 * @param endTime：结束时间
	 * @param checkIm：是否检测imsi和imei
	 * @param imsi：imsi的值
	 * @param imei：imei的值
	 */
	$.checkDateTime = function(beginTime, endTime, check) {
		if(check){
			if(!$.trim(beginTime) || !$.trim(endTime)){
				$.messager.alert('提示','请填写必填项！');
				return false;
			}
		}
		var begin = new Date(beginTime.replace(/-/g, '/'));
		var end = new Date(endTime.replace(/-/g, '/'));
		if (end < begin) {
			$.messager.alert('提示','开始日期小于结束日期， 请重新选择查询日期！');
			return false;
		}
		return true;
	};

	$.queryGrid = function(dataTableId, url, param) {
		var dtGrids = $('#' + dataTableId);
		$.showLoadMsg(dtGrids);
		$.post(url, param, function(data) {
			$.hideLoadMsg(dtGrids);
			var rows = $.parseJSON(data);
			dtGrids.datagrid('loadData', rows);
		});
	};
	/**
	 * 根据给定的html元素，寻找其范围内带有query样式的对象，并取出对应值，组成查询键值对
	 */
	$.getQueryParam = function(id) {
		var param = {};
		$('#' + id).find('.query').each(function() {
			var name = $(this).attr('name');
			var val = $(this).val();
			if ($(this).hasClass('combobox-f')) {
				name = $(this).attr('comboname');
				val = $(this).combobox('getValue');
			}
			if ($(this).hasClass('combogrid-f')) {
                name = $(this).attr('comboname');
                val = $(this).combogrid('getValue');
            }
            if ($(this).hasClass('combotree-f')) {
                name = $(this).attr('comboname');
                val = $(this).combotree('getValue');
            }
            if ($(this).hasClass('datebox-f')) {
                name = $(this).attr('comboname');
                val = $(this).datebox('getValue');
            }
            if ($(this).hasClass('datetimebox-f')) {
                name = $(this).attr('comboname');
                val = $(this).datetimebox('getValue');
            }
			param[name] = val;
		});
		return param;
	};
    $.request = function(url,paras){
        var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
        var paraObj = {},j;
        for (var i=0; j=paraString[i]; i++){
            paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);
        }
        var returnValue = paraObj[paras.toLowerCase()];
        if(typeof(returnValue)=="undefined"){
            return "";
        }else{
            return returnValue;
        }
    };
    $.getNodes = function($tree,node){
    	var id = node.id+"";
        if($.inArray(id,ids)==-1){
            ids.push(id);
        }
        var pnode = $tree.tree('getParent',node.target); //获取当前节点的父节点
        if(pnode){
            $.getNodes($tree,pnode);
        }
    };
})(jQuery);

//判断当前字符串是否以str开始 先判断是否存在function是避免和js原生方法冲突，自定义方法的效率不如原生的高
if (typeof String.prototype.startsWith != 'function') {
	String.prototype.startsWith = function(str) {
		return this.slice(0, str.length) == str;
	};
}
//判断当前字符串是否以str结束
if (typeof String.prototype.endsWith != 'function') {
	String.prototype.endsWith = function(str) {
		return this.slice(-str.length) == str;
	};
}


/**
 * queryuuid
 */
(function() {
	  // Private array of chars to use
	  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	 
	  Math.uuid = function (len, radix) {
	    var chars = CHARS, uuid = [], i;
	    radix = radix || chars.length;
	 
	    if (len) {
	      // Compact form
	      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
	    } else {
	      // rfc4122, version 4 form
	      var r;
	 
	      // rfc4122 requires these characters
	      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
	      uuid[14] = '4';
	 
	      // Fill in random data.  At i==19 set the high bits of clock sequence as
	      // per rfc4122, sec. 4.1.5
	      for (i = 0; i < 36; i++) {
	        if (!uuid[i]) {
	          r = 0 | Math.random()*16;
	          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
	        }
	      }
	    }
	 
	    return uuid.join('');
	  };
	 
	  // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
	  // by minimizing calls to random()
	  Math.uuidFast = function() {
	    var chars = CHARS, uuid = new Array(36), rnd=0, r;
	    for (var i = 0; i < 36; i++) {
	      if (i==8 || i==13 ||  i==18 || i==23) {
	        uuid[i] = '-';
	      } else if (i==14) {
	        uuid[i] = '4';
	      } else {
	        if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
	        r = rnd & 0xf;
	        rnd = rnd >> 4;
	        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
	      }
	    }
	    return uuid.join('');
	  };
	 
	  // A more compact, but less performant, RFC4122v4 solution:
	  Math.uuidCompact = function() {
	    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
	      return v.toString(16);
	    });
	  };
	})();